
#include <Wire.h>  // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306Wire.h" // legacy include: `#include "SSD1306.h"`
#include <ESP8266WiFi.h>
#include <MQTT.h>

const char* ssid = "Wi-Fi SSID";      // Wi-Fi SSID
const char* password = "XXXXXXXX";    // Wi-Fi Password

// MQTT info
const char* hostname = "m14.cloudmqtt.com";
int port = 13536;
const char* user = "xxxx";
const char* user_password = "xxxx";
const char* id = "";

SSD1306Wire  display(0x3C, 4, 5);

WiFiClient net;
MQTTClient client;

unsigned long lastMillis = 0;

void connect() {
  Serial.print("checking wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }

  Serial.print("\nconnecting...");
  while (!client.connect("esp8266", user, user_password)) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("\nconnected!");

  client.subscribe("/hello");
  // client.unsubscribe("/hello");
}

void messageReceived(String &topic, String &payload) {
  Serial.println("incoming: " + topic + " - " + payload);
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  display.init();

  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
  display.drawString(0, 0, "MQTT");
  display.display();

  client.begin(hostname, port, net);
  client.onMessage(messageReceived);

  connect();
}

void loop() {
  client.loop();
  delay(10);  // <- fixes some issues with WiFi stability

  if (!client.connected()) {
    connect();
  }

  // publish a message roughly every second.
//  if (millis() - lastMillis > 1000) {
//    lastMillis = millis();
//    client.publish("/hello", "world");
//  }
}
